// eslint-disable-next-line no-undef
const fs = require('fs')
// eslint-disable-next-line no-undef
const path = require('path')
// eslint-disable-next-line no-undef
const Sharp = require('sharp')

function isImageFile(extension) {
  // 判断是否为图片文件
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif']
  return imageExtensions.includes(extension.toLowerCase())
}

function getPath() {
  return path
}

function readDirectory(directory, callback) {
  // 读取文件目录（异步）
  fs.readdir(directory, (error, files) => {
    if (error) {
      callback(error, null)
    } else {
      callback(null, files)
    }
  })
}

function readDirectorySync(directory) {
  // 读取文件目录（同步）
  try {
    return fs.readdirSync(directory)
  } catch (error) {
    console.error(error)
  }
  return null
}

function createDirectory(directory, callback) {
  //创建文件夹
  if (!fs.existsSync(directory)) {
    fs.mkdir(directory, (error) => {
      if (error) {
        callback(error)
      } else {
        callback(null)
      }
    })
  } else {
    callback(null)
  }
}

function resizeExtension(inputPath, outputPath, extension) {
  // 修改图片后缀
  const outputFilePath = extension ? outputPath.replace(/\.[^.]+$/, `.${extension}`) : outputPath
  Sharp(inputPath).toFile(outputFilePath, (err) => {
    if (err) {
      console.error(err)
    } else {
      // console.log(`Resized image saved to ${outputPath}`);
    }
  })
}

function resizeImage(inputPath, outputPath, size, extension) {
  //修改图片尺寸
  const outputFilePath = extension ? outputPath.replace(/\.[^.]+$/, `.${extension}`) : outputPath
  const options = { ...size, quality: 80 }
  options.withoutEnlargement = true
  Sharp(inputPath)
    .resize(options)
    .toFile(outputFilePath, (err) => {
      if (err) {
        console.error(err)
      } else {
        // console.log(`Resized image saved to ${outputPath}`);
      }
    })
}

function addTextOnImage(inputPath, outputPath, msg, type, position) {
  try {
    if (type === 'font') {
      const width = 200
      const height = 200
      const svgImage = `
      <svg width='${width}' height='${height}'>
        <style>
        /*.title { fill: red; font-size: 40px; transform: rotate(45deg); transform-origin: center;}*/
        .title { fill: red; font-size: 20px;}
        </style>
        <text x='1%' class='title'>${msg}</text>
      </svg>
      `
      console.log(position)
      Sharp(inputPath)
        .composite([
          {
            input: Buffer.from(svgImage, 'utf-8'),
            gravity: 'southeast'
          }
        ])
        .toFile(outputPath)
    } else {
      Sharp(inputPath)
        .composite([
          {
            input: msg,
            gravity: position
          }
        ])
        .toFile(outputPath)
    }
  } catch (error) {
    console.log(error)
  }
}

window.service = {
  shellShowItemInFolder: function (path) {
    // 打开文件夹并选择文件
    if (!path) return
    // eslint-disable-next-line no-undef
    utools.shellShowItemInFolder(path)
  },

  openSelect: function () {
    // 打开弹窗选择文件
    // eslint-disable-next-line no-undef
    return utools.showOpenDialog({
      properties: ['openFile']
    })
  },

  openDirectory: function () {
    // 打开弹窗选择文件夹
    // eslint-disable-next-line no-undef
    return utools.showOpenDialog({
      properties: ['openDirectory']
    })
  },

  getFilesDirectory: function (directory) {
    //获取文件夹中的所有图片
    return this.getFiles(directory)
  },

  getFiles: function (directory) {
    // 获取文件夹中的所有文件
    const files = readDirectorySync(directory)
    if (files && Array.isArray(files)) {
      let path = getPath()
      return files.filter((file) => {
        return isImageFile(path.extname(file).toLowerCase())
      })
    }
    return []
  },

  changeImageExtensionExecution: function (inputDirectory, outputDirectory, extension, callback) {
    // 修改图片后缀
    readDirectory(inputDirectory, (error, files) => {
      if (error) {
        console.log(error)
      } else {
        createDirectory(outputDirectory, (error) => {
          if (error) {
            console.log(error)
          } else {
            let path = getPath()
            files.forEach((file) => {
              const inputPath = path.join(inputDirectory, file)
              const outputPath = path.join(outputDirectory, file)
              const fileExtension = path.extname(inputPath).toLowerCase()
              if (isImageFile(fileExtension)) {
                resizeExtension(inputPath, outputPath, extension)
              }
            })
            callback()
          }
        })
      }
    })
  },

  waterMarkImagesAction: function (inputDirectory, outputDirectory, msg, callback, type, position) {
    // 修改图片后缀
    readDirectory(inputDirectory, (error, files) => {
      if (error) {
        console.log(error)
      } else {
        createDirectory(outputDirectory, (error) => {
          if (error) {
            console.log(error)
          } else {
            let path = getPath()
            files.forEach((file) => {
              const inputPath = path.join(inputDirectory, file)
              const outputPath = path.join(outputDirectory, file)
              const fileExtension = path.extname(inputPath).toLowerCase()
              if (isImageFile(fileExtension)) {
                addTextOnImage(inputPath, outputPath, msg, type, position)
              }
            })
            callback()
          }
        })
      }
    })
  },

  modifyImagesExecution: function (inputDirectory, outputDirectory, size, extension, callback) {
    // 修改文件夹中的所有图片
    readDirectory(inputDirectory, (error, files) => {
      if (error) {
        console.log(error)
      } else {
        createDirectory(outputDirectory, (error) => {
          if (error) {
            console.log(error)
          } else {
            let path = getPath()
            files.forEach((file) => {
              const inputPath = path.join(inputDirectory, file)
              const outputPath = path.join(outputDirectory, file)
              const fileExtension = path.extname(inputPath).toLowerCase()
              if (isImageFile(fileExtension)) {
                resizeImage(inputPath, outputPath, size, extension)
              }
            })
            callback()
          }
        })
      }
    })
  },

  changeImageExtension: function (inputPath, outputPath, extension, callback) {
    // 修改图片格式
    if (inputPath && outputPath && extension) {
      this.changeImageExtensionExecution(inputPath, outputPath, extension, callback)
    } else {
      console.log('参数不完整')
    }
  },

  modifyImages: function (inputDirectory, outputDirectory, size, extension, callback) {
    // 修改图片尺寸
    if (inputDirectory && outputDirectory && size) {
      this.modifyImagesExecution(inputDirectory, outputDirectory, size, extension, callback)
    } else {
      console.log('参数不完整')
    }
  },

  waterMarkImages: function (inputDirectory, outputDirectory, msg, callback, type, position) {
    // 修改图片尺寸
    if (inputDirectory && outputDirectory && msg) {
      this.waterMarkImagesAction(inputDirectory, outputDirectory, msg, callback, type, position)
    } else {
      console.log('参数不完整')
    }
  }
}
